##### Loading Packages ####
packages <- c("dplyr",  "ggplot2", "conflicted",  "forcats", "stringr", "tidyr", 
              "ggpubr", "sf" )
sapply(packages, function(x){library(x, character.only = TRUE)})
conflict_prefer("select", "dplyr")
conflict_prefer("filter", "dplyr")
##### Loading data  ####
load("Data/ElectoralPetitionsData.RData")



####litigation rate per party per election ####
petitionsByLosingCandidate %>% 
  ungroup() %>% 
  mutate(party = case_when(party == "mmd" ~ "MMD", 
                           party == "pf" ~ "PF", 
                           party == "upnd" ~ "UPND", 
                           TRUE ~ "Other"), 
         party = as.factor(party), 
         party = fct_relevel(party,  c("Other", "MMD",  "UPND", "PF" ))) %>% 
  group_by(year, party) %>% 
  summarize(share_petitioned = mean(petition), 
            share_litigated = mean(petition_and_litigation)) %>% 
  pivot_longer(cols = c(-year, -party), 
               names_to = "challenge", 
               values_to = "share") %>% 
  ggplot(aes(x = party, y = share, fill = challenge))+
  geom_bar(stat = "identity", position = "dodge", 
           color = "black")+
  facet_wrap(~year) +
  coord_flip() +
  theme_classic()+
  theme(text = element_text(size = 20))+
  scale_fill_manual(values = c("cornflowerblue", "firebrick"),
                    labels = c("Share of losses litigated", "share of losses petitioned"), 
                    name = "")+
  xlab("") +
  ylab("Share of lost seats contested")+
  guides(fill = guide_legend(position = "bottom"))
ggsave(file = "FiguresAndTables/challenge_shares.png",
       height = 10,
       width = 10)  
  




#### Constituencies affected by electoral violence ####

violence <- petitionsByLosingCandidate %>% 
  ungroup() %>% 
  distinct(constituency, year, .keep_all = TRUE) %>% 
  select( year, acled_electoral_violence_dummy,  pre_election_violence2016,  reported_violence_ccmg21) %>% 
  mutate(pre_election_violence2016 = if_else(year != 2016, NA, pre_election_violence2016 )) %>% 
  group_by(year) %>% 
  summarize(acled_electoral_violence_dummy = sum(acled_electoral_violence_dummy, na.rm = TRUE), 
            pre_election_violence2016 = sum(pre_election_violence2016, na.rm = TRUE),
            reported_violence_ccmg21 = sum(reported_violence_ccmg21, na.rm = TRUE)) %>% 
  pivot_longer(cols = c(acled_electoral_violence_dummy, pre_election_violence2016, reported_violence_ccmg21), 
               names_to = "measure", 
               values_to = "count") %>% 
  mutate(measure = case_when(measure == "acled_electoral_violence_dummy" ~ "ACLED", 
                             measure == "pre_election_violence2016" ~ "ZEMS", 
                             measure == "reported_violence_ccmg21" ~ "CCMG")) %>% 
  ungroup()

violence2011 <- violence %>% 
  filter(year == 2011, count > 0) %>% 
  ggplot( aes(x = measure, 
              y = count))+
  geom_bar(stat = "identity", width = 0.45)+
  theme_classic()+
  theme(text = element_text(size = 16), 
        axis.line.x = element_blank(), 
        axis.ticks.x = element_blank(), 
        axis.text.x = element_blank())+
  labs(x = "", 
       y = "", 
       title = "2011")+
  coord_flip()+
  ylim(0,90)

violence2016 <- violence %>% 
  filter(year == 2016, count > 0) %>% 
  ggplot( aes(x = measure, 
              y = count))+
  geom_bar(stat = "identity")+
  theme_classic()+
  theme(text = element_text(size = 16), 
        axis.line.x = element_blank(), 
        axis.ticks.x = element_blank(), 
        axis.text.x = element_blank())+
  labs(x = "", 
       y = "", 
       title = "2016")+
  coord_flip()+
  ylim(0,90)

violence2021 <- violence %>% 
  filter(year == 2021, count > 0) %>% 
  ggplot( aes(x = measure, 
              y = count))+
  geom_bar(stat = "identity")+
  theme_classic()+
  theme(text = element_text(size = 16))+
  labs(x = "", 
       y = "Number of constituencies with reported violence", 
       title = "2021")+
  coord_flip()+
  ylim(0,90)


ggarrange(violence2011, 
          violence2016, 
          violence2021, 
          ncol = 1)

ggsave(file = "FiguresAndTables/reported_violence_measures.png",
       height = 10,
       width = 10)

violence_overlap <- petitionsByLosingCandidate %>% 
  subset(year>2011) |> 
  ungroup() %>% 
  distinct(constituency, year, .keep_all = TRUE) %>% 
  select( year, constituency, acled_electoral_violence_dummy,  pre_election_violence2016,  reported_violence_ccmg21) %>% 
  mutate(pre_election_violence2016 = if_else(year != 2016, NA, pre_election_violence2016 )) |> 
  mutate("acled_zems" = ifelse(acled_electoral_violence_dummy == 1 & pre_election_violence2016 == 1, "ACLED & ZEMS",
                               ifelse(acled_electoral_violence_dummy == 0 & pre_election_violence2016 == 1, "ZEMS",
                                      ifelse(acled_electoral_violence_dummy == 1 & pre_election_violence2016 == 0, "ACLED",
                                             ifelse(acled_electoral_violence_dummy == 0 & pre_election_violence2016 == 0, "Neither", "Error")))),
         "acled_ccmg" = ifelse(acled_electoral_violence_dummy == 1 & reported_violence_ccmg21 == 1, "ACLED & CCMG",
                               ifelse(acled_electoral_violence_dummy == 0 & reported_violence_ccmg21 == 1, "CCMG",
                                      ifelse(acled_electoral_violence_dummy == 1 & reported_violence_ccmg21 == 0, "ACLED",
                                             ifelse(acled_electoral_violence_dummy == 0 & reported_violence_ccmg21 == 0, "Neither", "Error"))))) |> 
  mutate("overlap" = ifelse(is.na(acled_zems)==TRUE, acled_ccmg, acled_zems))
violence_overlap$constituency_nr <- as.numeric(as.factor(violence_overlap$constituency))
violence_overlap$acled_zems <- factor(violence_overlap$acled_zems, levels = c("ACLED", "ZEMS", "ACLED & ZEMS", "Neither"))
violence_overlap$acled_ccmg <- factor(violence_overlap$acled_ccmg, levels = c("ACLED", "CCMG", "ACLED & CCMG", "Neither"))

plot_2016 <- violence_overlap |> subset(year==2016) |> 
  arrange(acled_zems) |> mutate("row" = 1:n()) |> 
  ggplot(aes(x = row, y = 1, fill = acled_zems)) +
  geom_tile() +
  ylab("") + xlab("Constituency") +
  scale_y_continuous(breaks = 1, labels = 2016) + 
  theme_classic() +
  theme(axis.text.y = element_text(angle = 0, vjust = 0.5, hjust=0,  size = 20),
        legend.title = element_blank())
plot_2021 <- violence_overlap |> subset(year==2021 & is.na(acled_ccmg) == FALSE) |> 
  arrange(acled_ccmg) |> mutate("row" = 1:n()) |> 
  ggplot(aes(x = row, y = 1, fill = acled_ccmg)) +
  geom_tile() +
  ylab("") + xlab("Constituency") +
  scale_y_continuous(breaks = 1, labels = 2021) + 
  theme_classic() +
  theme(axis.text.y = element_text(angle = 0, vjust = 0.5, hjust=0,  size = 20),
        legend.title = element_blank())
ggarrange(plot_2016, plot_2021, ncol = 1)
  

tmp <- data.frame(t(data.frame(table(violence_overlap$acled_zems))))
colnames(tmp) <- data.frame(table(violence_overlap$acled_zems))$Var1
tmp <- tmp[which(tmp$ACLED!="ACLED"),]
print(xtable::xtable(tmp, 
                     caption = "Number of constituencies with reported violence from different sources in 2016",
                     label = "tab:violence_overlap_2016",
                     align = "lrrrr"), include.rownames = FALSE,
      caption.placement = "top",
      table.placement = "!htbp",
      file = "FiguresAndTables/violence_overlap_2016.tex")
tmp <- data.frame(t(data.frame(table(violence_overlap$acled_ccmg))))
colnames(tmp) <- data.frame(table(violence_overlap$acled_ccmg))$Var1
tmp <- tmp[which(tmp$ACLED!="ACLED"),]
print(xtable::xtable(tmp, 
                     caption = "Number of constituencies with reported violence from different sources in 2021",
                     label = "tab:violence_overlap_2021", 
                     align = "lrrrr"), include.rownames = FALSE,
      caption.placement = "top",
      table.placement = "!htbp",
      file = "FiguresAndTables/violence_overlap_2021.tex")
rm(violence_overlap, tmp, plot_2016, plot_2021)




#### Bar chart of claims in 2011 petitions ####
bar_chart_claims <- petitionsByLosingCandidate %>% 
  ungroup() %>% 
  filter(year == 2011, petition == 1) %>% 
  select(ends_with("claim_dummy")) %>% 
  pivot_longer(cols = everything(), 
               names_to = "type", 
               values_to = "claimed") %>% 
  group_by(type) %>% 
  summarize(claims = sum(claimed, na.rm = TRUE)) %>% 
  mutate(type = case_when(type == "petition_abuse_state_resouces_claim_dummy" ~ "Abuse of state resources", 
                          type == "petition_bribery_or_treating_claim_dummy" ~ "Vote buying, bribery, or treating of voters", 
                          type == "petition_campaigning_outside_campaign_period_claim_dummy" ~ "Campaigning outside official campaign period",
                          type == "petition_ferrying_voters_claim_dummy"  ~ "Ferrying of voters", 
                          type == "petition_intimidation_claim_dummy" ~ "Intimidation of voters or other political parties", 
                          type == "petition_malicious_statements_claim_dummy" ~ "Malicious or false statements about opponents", 
                          type == "petition_other_claim_dummy" ~ "Other alleged violations of the Electoral Code", 
                          type == "petition_violence_claim_dummy" ~ "Violence", 
                          type == "petition_voting_or_count_irregularities_claim_dummy" ~ "Irregularities at polling station or during counting"), 
         type  = str_wrap(type, width = 20)) %>% 
  ggplot(aes(x = fct_reorder(type,  claims),
             y = claims)) +
  geom_bar(stat = "identity")+
  coord_flip()+
  theme_classic()+
  theme(text = element_text(size = 16))+
  labs(x = "", 
       y = "Number of petitions with claim")



### Number of distinct types of claims per petition
claim_types_per_petition <-petitionsByLosingCandidate %>% 
  ungroup() %>% 
  filter(year == 2011, petition == 1) %>% 
  select(c(high_court_case_number, ends_with("claim_dummy"))) %>% 
  pivot_longer(cols = ends_with("claim_dummy"), 
               names_to = "type", 
               values_to = "claimed") %>% 
  drop_na() %>% 
  group_by(high_court_case_number) %>% 
  summarize(claim_types = sum(claimed))
summary(claim_types_per_petition$claim_types)

claim_types_per_petition_chart <- claim_types_per_petition %>% 
  ggplot(aes(x = claim_types)) +
  geom_bar()+
  theme_classic()+
  theme(text = element_text(size = 16)) +
  scale_x_continuous(breaks = 1:8, 
                     labels = 1:8) +
  scale_y_continuous(breaks = 1:12, 
                     labels = 1:12)+
  labs(y = "Number of petitions", 
       x = "Distinct types of claims")
  
  
ggarrange(bar_chart_claims, claim_types_per_petition_chart, 
          nrow = 1)  
  
ggsave(file = "FiguresAndTables/claims2011.jpg",
         height = 10,
         width = 10)


##### Making maps #####
map_petitions_2011 <- ggplot(data = constituencies2011, 
                             aes(fill = Petitioned)) +
  geom_sf() +
  theme_classic()+
  scale_fill_manual(values = c("darkred", "grey"))+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Petitions against parliamentary elections (2011)")

map_petitions_2016 <- ggplot(data = constituencies2016, 
                             aes(fill = Petitioned)) +
  geom_sf() +
  theme_classic()+
  scale_fill_manual(values = c("darkred", "grey"))+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Petitions against parliamentary elections (2016)")

map_petitions_2021 <- ggplot(data = constituencies2021, 
                             aes(fill = Petitioned)) +
  geom_sf() +
  theme_classic()+
  scale_fill_manual(values = c("darkred", "grey"))+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Petitions against parliamentary elections (2021)")


ggarrange(map_petitions_2011, map_petitions_2016,map_petitions_2021)

map_seats_won_2011 <- ggplot(data = constituencies2011, 
                             aes(fill = Won_by)) +
  geom_sf() +
  scale_fill_manual(values = c("cornflowerblue", "darkgreen", "yellow","grey"))+
  theme_classic()+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Winning party in each constituency (2011)")

map_seats_won_2016 <- ggplot(data = constituencies2016, 
                             aes(fill = Won_by)) +
  geom_sf() +
  scale_fill_manual(values = c("cornflowerblue", "darkgreen", "yellow","grey"))+
  theme_classic()+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Winning party in each constituency (2016)")


map_seats_won_2021 <- ggplot(data = constituencies2021, 
                             aes(fill = Won_by)) +
  geom_sf() +
  scale_fill_manual(values = c( "darkgreen","yellow", "grey"))+
  theme_classic()+
  theme(legend.title = element_blank(), 
        legend.position = "bottom",
        axis.line = element_blank(), 
        axis.ticks = element_blank(), 
        axis.text = element_blank())+
  ggtitle("Winning party in each constituency (2021)")



ggarrange( map_seats_won_2011, map_petitions_2011,
           map_seats_won_2016, map_petitions_2016,
           map_seats_won_2021, map_petitions_2021, nrow = 3, ncol = 2)


ggsave(file = "FiguresAndTables/maps_with_winning_party_and_petitions.jpg",
       height = 10,
       width = 10)







finalOutcomesByPetitionerParty <- ggplot(filter(petitionsByLosingCandidate, petition == 1),
                                         aes(x = factor(candidate_party_four_categories,
                                                        levels = c("MMD", "PF", "UPND", "Other")),
                                             fill = factor(final_outcome, 
                                                           levels = c("Election nullified",
                                                                      "Petition dismissed", 
                                                                      "Withdrawn or discontinued", 
                                                                      "Not yet decided in\nConstitutional Court", 
                                                                      "Retrial ordered"))))+
  facet_grid(cols = vars(year_character))+
  geom_bar() +
  scale_fill_manual(values = c("firebrick", "dodgerblue", "forestgreen", "black", "purple"))+
  # scale_fill_grey()+
  theme_classic()+
  guides(fill=guide_legend("Final outcome")) +
  xlab("Party of Petitioner")+
  ylab("Number of Petitions")+
  theme(text = element_text(size = 16))+
  ylim(0,55)

highCourtOutcomesByPetitionerParty <- ggplot(filter(petitionsByLosingCandidate, petition == 1),
                                             aes(x = factor(candidate_party_four_categories,
                                                            levels = c("MMD", "PF", "UPND", "Other")),
                                                 fill = factor(high_court_outcome, 
                                                               levels = c("Election nullified",
                                                                          "Petition dismissed", 
                                                                          "Withdrawn or discontinued", 
                                                                          "Not yet decided in\nConstitutional Court", 
                                                                          "Retrial ordered"))))+
  facet_grid(cols = vars(year_character))+
  geom_bar() +
  scale_fill_manual(values = c("firebrick", "dodgerblue", "forestgreen", "black", "purple"))+
  #scale_fill_grey()+
  theme_classic()+
  guides(fill=guide_legend("High Court outcome")) +
  xlab("Party of Petitioner")+
  ylab("Number of Petitions")+
  theme(text = element_text(size = 16))+
  ylim(0,55)

appealOutcomesByPetitionerParty <-  ggplot(filter(petitionsByLosingCandidate, high_court_ruling_appealed == "yes"),
                                           aes(x = factor(candidate_party_four_categories,
                                                          levels = c("MMD", "PF", "UPND", "Other")),
                                               fill = factor(appeal_outcome,
                                                             levels = c("Election nullified", "Petition dismissed", "Appeal withdrawn", 
                                                                        "Not yet decided in\nConstitutional Court", "Retrial ordered"))))+
  facet_grid(cols = vars(year_character))+
  geom_bar() +
  scale_fill_manual(values = c("firebrick", "dodgerblue", "forestgreen", "black", "purple"))+
  #scale_fill_grey()+
  theme_classic()+
  guides(fill=guide_legend("Supreme/Constitutional\nCourt outcome")) +
  xlab("Party of Petitioner")+
  ylab("Number of Petitions")+
  theme(text = element_text(size = 16))+
  ylim(0,55)

ggarrange(finalOutcomesByPetitionerParty,
          highCourtOutcomesByPetitionerParty,
          appealOutcomesByPetitionerParty,
          nrow = 3)
ggsave(file = "FiguresAndTables/outcomes_by_party_and_year.jpg",
       height = 10,
       width = 10)



petitionsByLosingCandidate %>% 
  filter(is.na(high_court_judge) == FALSE) %>% 
  distinct(constituency, year_character, .keep_all  = TRUE) %>% 
  mutate(appointing_party_high_court_judge = toupper(appointing_party_high_court_judge)) %>% 
  group_by(year_character, high_court_judge, appointing_party_high_court_judge) %>% 
  summarize(cases_allocated = n()) %>% 
  ungroup() %>% 
  ggplot(aes(x = cases_allocated, fill = appointing_party_high_court_judge)) +
  geom_bar(stat = "count") +
  facet_grid(cols = vars(year_character)) +
  xlab("Number of electoral petitions decided by each High Court judge")+
  ylab("Number of High Court Judges") +
  scale_fill_manual(name = "Party of appointing\npresident", values = c("firebrick", "dodgerblue")) +
  theme_classic()+
  theme(text = element_text(size = 20))

ggsave(file = "FiguresAndTables/number_of_case_per_high_court_judge.jpg",
       height = 10,
       width = 10)




petitionsByLosingCandidate$respondent_party_four_categories

judge_and_petitioner_party <- petitionsByLosingCandidate %>% 
  filter(is.na(high_court_judge) == FALSE & high_court_outcome !=  "Withdrawn or discontinued") %>% 
  distinct(constituency, year_character, .keep_all  = TRUE) %>% 
  mutate(appointing_party_high_court_judge = toupper(appointing_party_high_court_judge)) %>% 
  group_by(year_character, appointing_party_high_court_judge, candidate_party_four_categories) %>% 
  summarize(nullifications = sum(nullified_by_high_court, na.rm = TRUE)) %>% 
  ungroup() %>% 
  mutate(candidate_party_four_categories = fct_relevel(candidate_party_four_categories, 
                                                       "MMD", "PF", "UPND", "Other")) %>% 
  ggplot(aes(x = appointing_party_high_court_judge, y = nullifications, fill = candidate_party_four_categories)) +
  geom_bar(stat = "identity") +
  facet_grid(cols = vars(year_character)) +
  scale_fill_manual(name = "Party of petitioner", values = c("cornflowerblue", "darkgreen", "yellow","grey"))+
  xlab("Party of appointing president")+
  ylab("Number of elections nullified") +
  theme_classic()



judge_and_respondent_party <- petitionsByLosingCandidate %>% 
  filter(is.na(high_court_judge) == FALSE & high_court_outcome !=  "Withdrawn or discontinued") %>% 
  
  distinct(constituency, year_character, .keep_all  = TRUE) %>% 
  mutate(appointing_party_high_court_judge = toupper(appointing_party_high_court_judge)) %>% 
  group_by(year_character, appointing_party_high_court_judge, respondent_party_four_categories) %>% 
  summarize(nullifications = sum(nullified_by_high_court, na.rm = TRUE)) %>% 
  ungroup() %>% 
  mutate(respondent_party_four_categories = fct_relevel(respondent_party_four_categories, 
                                                        "MMD", "PF", "UPND", "Other")) %>% 
  ggplot(aes(x = appointing_party_high_court_judge, y = nullifications, fill = respondent_party_four_categories)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(name = "Party of respondent", values = c("cornflowerblue", "darkgreen", "yellow","grey"))+
  facet_grid(cols = vars(year_character)) +
  xlab("Party of appointing president")+
  ylab("Number of elections nullified") +
  theme_classic()

ggarrange(judge_and_petitioner_party, 
          judge_and_respondent_party, ncol = 1 )



ggsave(file = "FiguresAndTables/number_of_case_nullifed_by_judge_party.jpg",
       height = 10,
       width = 10)



petitionsByLosingCandidate %>% 
  filter(is.na(high_court_judge) == FALSE & high_court_outcome !=  "Withdrawn or discontinued") %>% 
  
  distinct(constituency, year_character, .keep_all  = TRUE) %>% 
  mutate(appointing_party_high_court_judge = toupper(appointing_party_high_court_judge)) %>% 
  group_by(year_character, appointing_party_high_court_judge) %>% 
  summarize(nullifications = mean(nullified_by_high_court, na.rm = TRUE)) %>% 
  ungroup()  %>% 
  ggplot(aes(x = appointing_party_high_court_judge, y = nullifications)) +
  geom_bar(stat = "identity") +
  # scale_fill_manual(name = "Party of respondent", values = c("cornflowerblue", "darkgreen", "yellow","grey"))+
  facet_grid(cols = vars(year_character)) +
  xlab("Party of appointing president")+
  ylab("Share of elections nullified") +
  
  theme_classic()+
  theme(text = element_text(size = 20))

ggsave(file = "FiguresAndTables/share_of_case_nullifed_by_judge_party.jpg",
       height = 10,
       width = 10)

